package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    private static final String WECHAT_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
    @Resource
    private WeChatProperties weChatProperties;
    @Resource
    private JwtProperties jwtProperties;
    @Resource
    private UserMapper userMapper;
    /**
     * 使用用户小程序登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        //1. 发送请求给微信，获取openid
        String openId = getOpenId(userLoginDTO.getCode());
        //2. 如果没有openid则登录失败
        if(ObjectUtils.isEmpty(openId)){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //3. 有openid，通过openid查询数据库用户表中是否存在
        User user = userMapper.getByOpenid(openId);
        //4. 用户不存在
        if(null == user) {
            //4.1 不存在则构建user对象，保存到用户表中，自动注册为用户
            user = User.builder().openid(openId)
                .createTime(LocalDateTime.now())
                .build();
            userMapper.insert(user);
        }
        //5. 生成token
        //为微信用户生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        //6. 构建vo返回
        UserLoginVO vo = UserLoginVO.builder()
            .id(user.getId())
            .openid(openId)
            .token(token)
            .build();
        return vo;
    }

    /**
     * 发送请求给微信
     * @param code
     * @return
     */
    private String getOpenId(String code) {
        // 构建微信登录的请求参数
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid",weChatProperties.getAppid());
        paramMap.put("secret",weChatProperties.getSecret());
        paramMap.put("js_code",code);
        paramMap.put("grant_type","authorization_code");
        // 发送请求,微信响应的json数据
        String resultString = Optional
            .ofNullable(HttpClientUtil
                .doGet(UserServiceImpl.WECHAT_LOGIN_URL, paramMap))
            .orElseThrow(()->new LoginFailedException(MessageConstant.LOGIN_FAILED));
        //得到openid

        JSONObject jsonObject = JSON.parseObject(resultString);
        //判断不程序登录在微信是否真的成功
        String errcode = jsonObject.getString("errcode");
        if (null != errcode && !"0".equals(errcode)) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        // 获取openid字段的值
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
